<template>
  <div>
    <el-input
      v-show="search"
      :placeholder="placeholder"
      v-model="filterText" size="small">
    </el-input>
    <div class="el-tree" :class="{ 'el-tree--highlight-current': highlightCurrent }">
      <el-tree-node
        v-for="child in root.childNodes"
        :node="child"
        :props="props"
        :key="getNodeKey(child)"
        :render-content="renderContent"
        @node-expand="handleNodeExpand">
      </el-tree-node>
      <div class="el-tree__empty-block" v-if="!root.childNodes || root.childNodes.length === 0">
        <span class="el-tree__empty-text">{{ emptyText }}</span>
      </div>
    </div>
  </div>
</template>

<script>
  import fetch from '@/utils/fetch';
  import {Tree} from 'element-ui';
  import {list2tree} from '@/utils/treeUtils';

  delete Tree.props.data;

  export default {
    data() {
      return {
        data: [],
        filterText: null,
      };
    },
    watch: {
      filterText(val) {
        this.filter(val);
      },
    },
    mixins: [Tree],
    props: {
      search: {
        type: Boolean,
        default: false,
      },
      placeholder: {type: String},
      filterNodeMethod: {
        type: Function, default: function(value, data) {
          if (!value) return true;
          return data.label.indexOf(value) !== -1;
        },
      },
      defaultProps: {
        default() {
          return {
            children: 'children',
            label: 'label',
          };
        },
      },
      filterNode: {
        type: Function,
      },
    },
    created() {
      const _this = this;
      httpClient.default(() => fetch({
        url: '/gi-paas-sd-sqlcomputesvc/api/service/querySql',
        method: 'put',
        data: {
          'position': 'projectStructure_queryProjectTree',
          'paramMap': {},
        },
      }), function(error, result) {
        _this.$emit('loaded', result);
        if (_this.filterNode) {
          result = result.filter(item => _this.filterNode(item));
        }
        result.forEach(item => {
          if (item.parentId) {
            //分期楼栋
            item.label = item.name;
          } else {
            //项目
            item.label = item.projectName;
            item.parentId = null;
          }
        });
        _this.data = list2tree(result);
      });
    },
  };

</script>
